package com.ziroom.finance.rabbitmq.common.base;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 文件上传及下载
 * @author gaocy15
 *
 */
public class FTPUpOrLoadFile {
	
	private static final transient Logger LOGGER = LoggerFactory.getLogger(FTPUpOrLoadFile.class);
	
	/**
	 * Description: 向FTP服务器上传文件
	 * @param url FTP服务器hostname
	 * @param port FTP服务器端口
	 * @param username FTP登录账号
	 * @param password FTP登录密码
	 * @param path FTP服务器保存目录
	 * @param filename 上传到FTP服务器上的文件名
	 * @param input 输入流
	 * @return 成功返回true，否则返回false
	 */
	public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);//连接FTP服务器
			LOGGER.info("====开始登陆ftp服务器====="+"url="+url+",port="+port+",username="+username+",password="+password+",fileName="+filename);
			//如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);//登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				LOGGER.info("====ftp服务器登陆失败=====");
				ftp.disconnect();
				return success;
			}
			LOGGER.info("====ftp服务器登陆成功=====");
			//ftp.makeDirectory(path);
			// 设置文件类型（二进制）  
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
			ftp.changeWorkingDirectory(path);
			ftp.setBufferSize(1024);  
			ftp.setControlEncoding("GBK");  
	         
			success = ftp.storeFile(filename, input);			
			
			input.close();
			ftp.logout();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
	
	/**
	 * Description: 从FTP服务器下载文件 
	 * @param url FTP服务器hostname
	 * @param port FTP服务器端口
	 * @param username FTP登录账号
	 * @param password FTP登录密码
	 * @param remotePath FTP服务器上的相对路径
	 * @param fileName 要下载的文件名
	 * @param localPath 下载后保存到本地的路径
	 * @return
	 */
	public static boolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) {
		boolean success = false;
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect(url, port);
			LOGGER.info("====开始登陆ftp服务器====="+"url="+url+",port="+port+",username="+username+",password="+password+",fileName="+fileName);
			//如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.login(username, password);//登录
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				LOGGER.info("====ftp服务器登陆失败=====");
				ftp.disconnect();
				return success;
			}
			LOGGER.info("====ftp服务器登陆成功=====");
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
			ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
			FTPFile[] fs = ftp.listFiles();
			for(FTPFile ff:fs){
				if(ff.getName().equals(fileName)){
					File localFile = new File(localPath+"/"+ff.getName());
					
					OutputStream is = new FileOutputStream(localFile); 
					success = ftp.retrieveFile(ff.getName(), is);
					is.close();
				}
			}
			
			ftp.logout();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
				}
			}
		}
		return success;
	}
	
	/**
	 * Description: 从FTP服务器下载文件 输出字节流
	 * @param url FTP服务器hostname
	 * @param port FTP服务器端口
	 * @param username FTP登录账号
	 * @param password FTP登录密码
	 * @param remotePath FTP服务器上的相对路径
	 * @param fileName 要下载的文件名
	 * @return
	 */
	 public static ByteArrayOutputStream downFile(String url, int port,String username, String password, String remotePath,String fileName) {
			ByteArrayOutputStream outByte = null ;
			FTPClient ftp = new FTPClient();
			try {
				int reply;
				ftp.connect(url, port);
				LOGGER.info("====开始登陆ftp服务器====="+"url="+url+",port="+port+",username="+username+",password="+password+",fileName="+fileName);
				//如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
				ftp.login(username, password);//登录
				reply = ftp.getReplyCode();
				if (!FTPReply.isPositiveCompletion(reply)) {
					LOGGER.info("====ftp服务器登陆失败=====");
					ftp.disconnect();
					return outByte;
				}
				LOGGER.info("====ftp服务器登陆成功=====");
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE); 
				ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
				FTPFile[] fs = ftp.listFiles();
				for(FTPFile ff:fs){
					if(ff.getName().equals(fileName)){
						outByte = new ByteArrayOutputStream();
						boolean success = ftp.retrieveFile(ff.getName(), outByte);
						if(success){
							outByte.close();
							return outByte ;
						}
					}
				}
				
				ftp.logout();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (ftp.isConnected()) {
					try {
						ftp.disconnect();
					} catch (IOException ioe) {
					}
				}
			}
			return outByte;
		}
	
	  /**
	   * 网络文件下载
	   * @return
	   * @throws Exception
	   */
	  public static boolean downloadNet(String filePath) throws Exception {
		  
		  	boolean flag = false ;
	        int bytesum = 0;
	        int byteread = 0;
	        //http://10.16.34.48:8080/group1/M00/01/86/ChAiMFght7yAGnNdAAIQ3_bzHl0145.pdf
	        URL url = new URL(filePath);
	        FileOutputStream fs = null ;
	        try {
	            URLConnection conn = url.openConnection();
	            InputStream inStream = conn.getInputStream();
	            fs = new FileOutputStream("e:/ChAiMFght7yAGnNdAAIQ3_bzHl0145.pdf");
	            
	            byte[] buffer = new byte[1204];
	            int length;
	            while ((byteread = inStream.read(buffer)) != -1) {
	                bytesum += byteread;
	                fs.write(buffer, 0, byteread);
	            }
	            
	            flag = true ;
	        } catch (Exception e) {
	            e.printStackTrace();
	        }finally{
	        	fs.close();
	        }
	        return flag ;
	    }
	  
	  public static InputStream getInputStream(String fileUrl)throws Exception{
		    LOGGER.info("文件url为"+fileUrl);
		    URL url = new URL(fileUrl);
			HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
			urlCon.setConnectTimeout(30000);  
			urlCon.setReadTimeout(30000);
			LOGGER.info("开始获取输入流inStream");
	        InputStream inStream = urlCon.getInputStream();
	        LOGGER.info("获取输入流inStream=="+inStream);
	        return inStream ;
	  }
}
